﻿import Taro, { Component } from '@tarojs/taro'
import { Swiper, SwiperItem, Image, View, Text, RichText,  Button } from '@tarojs/components'
import '../../assets/common.scss'
import CommonJs from '../../utils/common'
import './pkgodetails.scss'

export default class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      content:{},//活动详情
      pics:[],//活动详情图片
      photoList:[],//报名用户信息列表
      specificationsList:{},
      isload:0,//判断页面是否加载完成
      alertnum:0,
      resultnum:1,
      indexs:0,
      zhuliList:[],
      ruleList:[],
      joinnum:0,
      singleperson:[],
      singlepersonLen: '',
      nowDate: 0,
      myTime: null,
      joinlist: [],
      joinrenshu: 0,
      joinTime: 0,
      joinrenshulist: [],
      amount: 0,
      specSerial: '',
      mallPrice: 0,
      shareUid: '',
      groupbuer: false,
      groupId: '',
      pageName: ''
    }
  }
  config = {
    navigationBarTitleText: '加载中'
  }

  componentWillMount () {
    this.getdata()
    this.getphoto()
    // this.getspecifications()
    
    this.getrule()
   
  }

  componentDidMount () {
  }

  componentWillUnmount () { }

  componentDidShow () {
    let data = this.$scope.data
    let groupbuer = data.groupbuer
    // console.log(ischange)
    if (groupbuer) {
      let pageName = data.pageName
      let id = data.groupId
      this.setState({
        groupbuer: false,
        groupId: id,
        pageName: pageName
      })
      this.openalert()
    }
  }

  componentDidHide () { }

  opendetails(url){
    var _this = this
    var specificationsList = _this.state.specificationsList
    var pageName = _this.state.pageName
    var aar = []
    var obj = {}
    if (pageName == 'freegoodsDetails') {//PK购按钮
      obj.businessType = 4
      obj.shopCommodityId = specificationsList.shopCommodity.id
      obj.clusterId = _this.state.groupId
    }
    obj.id = specificationsList.goodsInventoryResult.id
    obj.logo = specificationsList.shopCommodity.logo
    obj.commodityName = specificationsList.shopCommodity.commodityName
    obj.price = _this.state.mallPrice
    obj.amount = _this.state.resultnum
    obj.goodsName = _this.state.specSerial
    obj.dealerId = specificationsList.shopCommodity.dealerId
    obj.dealerName = specificationsList.shopCommodity.dealerName
    obj.shopId = specificationsList.shopCommodity.shopId
    obj.shopName = specificationsList.shopCommodity.shopName
    obj.commodityId = specificationsList.shopCommodity.commodityId
    obj.needToDistribute = specificationsList.shopCommodity.needToDistribute
    aar.push(obj)
    // console.log(JSON.stringify(aar))
    if (pageName == 'freegoodsDetails') {
      _this.$preload({
        aar: aar,
        freetype: 1
      })
    } else {
      _this.$preload({
        aar: aar
      })
    }
    CommonJs.openTo(url)
  }
  
  open(url){
    CommonJs.open(url);
  }
  getdata(){
    //商品详情
    var _this=this;
    //console.log(JSON.stringify(_this.$router)+'2222222222')
    var date = {
      commodityId:_this.$router.preload.commodityId,
      shopId:_this.$router.preload.shopId
    }
    CommonJs.ajaxRequest('/shop/getShopCommodityByCommodityIdAndShopId',date,'GET',function(res){
      // console.log(JSON.stringify(res)+'2222222222')
      Taro.setNavigationBarTitle({title:"商品详情"})
      _this.setState({
        content: res.content
      })
	 
	  _this.getpdlist(res.content.id)
	  _this.getzhuli(res.content.id)
	  
    })
  }
  getphoto(){
    //获取详情长图
    var _this=this;
    var date = {
      id:_this.$router.preload.commodityId,
      roleTypeId:1003
    }
    CommonJs.ajaxRequest('/commodity/getDetail',date,'GET',function(res){
        // console.log(JSON.stringify(res)+'6666666666777777777777')
        _this.setState({
          photoList: res.content
        });
    })
  }
  getrule(){
    //获取活动规则
    var _this=this;
    var date = {
      type:22
    }
    CommonJs.ajaxRequest('/other/getMessageByType',date,'GET',function(res){
        // console.log(JSON.stringify(res)+'6666666666777777777777')
        _this.setState({
          ruleList: res
        });
    })
  }
  getzhuli(id){
    //获取助力信息
    var _this=this;
    var date = {
      shopCommodityId:id
    }
    CommonJs.ajaxRequest('/freeGoSetting/getFreeGoSettingByShopCommodityId',date,'GET',function(res){
        // console.log(JSON.stringify(res)+'6666666666777777777777')
        _this.setState({
          zhuliList: res.content
        });
    })
  }

  getspecifications(){
    //商品规格
    var _this=this;
    var date = {
      commodityId:_this.$router.preload.commodityId,
      shopId:_this.$router.preload.shopId
    }
    ///commodity/getGoodsInventories
    CommonJs.ajaxRequest('/shop/getRelevantInforOfSpec',date,'GET',function(res){
      // console.log(JSON.stringify(res)+'6666666666777777777777')
      var specSerial = ''
      var specSerials = res.content.goodsInventoryResult.specSerial
      if (specSerials.indexOf(':') != -1) {
        specSerial = specSerials.split(':')[1]
      } else {
        specSerial = specSerials
      }
      // console.log(specSerial)
      _this.setState({
        specificationsList: res.content,
        alertnum: 1,
        amount: res.content.goodsInventoryResult.amount,
        specSerial: specSerial,
        mallPrice: res.content.goodsInventoryResult.mallPrice,
        indexs: 0
      })
    })
  }
  
  openalert(){
    var _this=this
    _this.getspecifications()
  }
  openaddclass(index, specSerial){
    var _this = this
    _this.setState({
      indexs:index,
      specSerial: specSerial
    })
    _this.countPM(specSerial)
  }
  openjoin(freeGoOrderId, joinrenshu, joinTime, shareUid){
    var _this=this
    var date = {
      freeGoOrderId: freeGoOrderId
    }
    CommonJs.ajaxRequest('/freeGoOrderUser/getFreeGoOrderUserList',date,'GET',function(res){
        // console.log(JSON.stringify(res)+'666666666wwwwwwwwww7').0
        if (res) {
          var joinrenshulist = []
          for (var i = 0; i < joinrenshu; i++) {
            joinrenshulist.push('wenhaox')
          }
          _this.setState({
            joinnum: 1,
            joinlist: res,
            joinrenshu: joinrenshu,
            joinTime: joinTime,
            joinrenshulist: joinrenshulist,
            shareUid: shareUid
          })
        }
    })
  }
  closealert(){
    var _this=this;
    _this.setState({
      alertnum: 0
    })
  }
  closejoin(){
    var _this=this;
    _this.setState({
      joinnum: 0,
      joinlist: []
    })
  }
  reducenum(){
    var _this=this;
    var resultnum = _this.state.resultnum;
    resultnum = resultnum - 1;
   if(resultnum<=0){
    Taro.showToast({
      title:'亲，至少也要买一件哦~~',
      icon: 'none',
      duration: 2000
    });
    return;
   }
    _this.setState({
      resultnum: resultnum
    });
  }
  addnum(){
    var _this=this;
    var resultnum = _this.state.resultnum;
    resultnum = resultnum + 1;
    var amount = _this.state.amount;
    if(resultnum>amount){
      Taro.showToast({
      title:'亲，已超过库存数量哦~~',
      icon: 'none',
      duration: 2000
    });
    return;
    }
    _this.setState({
        resultnum: resultnum
      });
  }
  preventTouchMove(event){
    //自定义弹窗防止出现蒙层还可以滑动
    event.stopPropagation()
  }
  getpdlist(id){
    //当前商品拼单人列表 
	// console.log(id+"/////ddddddddddddddddddddddd")
    var _this = this
    var freeGoOrderId = _this.$router.preload.freeGoOrderId
	if(id){
		var date = {
		  shopCommodityId:id,
		  statusList: 2,
		  pageSize: 1000
		}
		CommonJs.ajaxRequest('/freeGoOrder/freeGoOrderPageData',date,'GET',function(res){
		  if (res) {
			var result = res.result
			_this.setState({
			  singleperson: result,
			  singlepersonLen: res.totalCount
			})
			_this.countDown()
			if (freeGoOrderId != ''&&result.length>0) {
			  //判断上个页面传freeGoOrderId  从聊天点进来或者点击去PK执行该方法  pK免费购不执行
			  //请求数据显示弹窗
			  for(var i=0;i<result.length;i++){
				if(result[i].id==freeGoOrderId){
					_this.openjoin(freeGoOrderId, result[i].theNumberOfRemCoUsers, result[i].expiredCollageTime, result[i].shareUid)
				}
			  }
			  
			}
			
		  }
		})
	}
  }
  countDown(){
    //获取当前时间
    var _this = this
    var date = new Date()
    var nowDate = date.getTime()
    _this.setState({
      nowDate: nowDate 
    })
    _this.myTime = setTimeout(() => { _this.countDown() }, 1000)
  }
  countDowns(dates,times,shopCommodityId){
    //倒计时处理
    var _this = this
    if (dates == times) {
      clearTimeout(_this.myTime)
      _this.getpdlist(shopCommodityId)
    } else {
      return CommonJs.countDowns(dates, times)
    }
  }
  countPM(specSerial){
    var _this=this
    var content = _this.state.content
    var date = {
      commodityId: content.commodityId,
      shopId: content.shopId,
      dealerId: content.dealerId,
      roleTypeId: 1003,
      specSerial: specSerial
    }
    CommonJs.ajaxRequest('/commodity/getGoodsInventoryResultBySpecSerial',date,'GET',function(res){
        // console.log(JSON.stringify(res)+'666666666wwwwwwwwww7')
        if (res) {
          _this.setState({
            amount: res.content.amount,
            mallPrice: res.content.mallPrice
          })
        }
    })
  }
  canyupk(){
    var _this=this
    var shareUid = _this.state.shareUid
    var date = {
      shareUid: shareUid
    }
    CommonJs.ajaxRequest('/freeGoOrder/getFreeGoOrderByShareUid',date,'GET',function(res){
        // console.log(JSON.stringify(res)+'666666666wwwwwwwwww7')
        if (res) {
          if (res.code!=300) {
            var aar=[]
            var obj = {}              
            obj.id =res.content.goodsId
            obj.logo =res.content.commodityLogo
            obj.commodityName = res.content.commodityName
            obj.price =res.content.commodityPrice
            obj.amount = res.content.amount
            obj.goodsName = res.content.goodsName                       
            obj.dealerId = res.content.dealerId
            obj.dealerName = ''              
            obj.shopId = res.content.shopId
            obj.shopName = res.content.shopName
            obj.commodityId = res.content.commodityId;  
            obj.needToDistribute = ''
            obj.clusterId=0
            obj.shopCommodityId=res.content.shopCommodityId
            obj.shareUid=_this.state.shareUid
            obj.businessType=4
            aar.push(obj)
            _this.setState({
              joinnum: 0
            })
            _this.$preload({
              aar: aar,
              freetype: 1
            })
            CommonJs.openTo('/pages/pkgo/confirmorder')
          }
        }
    })
  }
  jump(url){
    CommonJs.openTo(url)
  }
  render () {
    const specificationsList = this.state.specificationsList
    const singleperson = this.state.singleperson
    const joinlist = this.state.joinlist
    const joinrenshulist = this.state.joinrenshulist
    let conten = this.state.photoList.content
    let contentt = String(conten)
    let contents = contentt.replace(/\<img/g, '<img style="width:100%;height:auto;display:block"')
    //原来的返回
    // <View className='qun-back' onClick={this.opendetails.bind(this,'/pages/activity/activity','')}><Image className='qun-backimg' src={backwmall}></Image></View>
    return (
      <View className='page'>
        <View className='banner'>
          <View className='qun-bg'>
            <Swiper className='qun-swiper' indicator-dots='true'  autoplay='true'>
              <SwiperItem>
                <Image className='qun-pic' src={content.logo}></Image>
              </SwiperItem>
              <SwiperItem>
                <RichText nodes={contents}></RichText>
              </SwiperItem>
            </Swiper>
            <View className='qun-name'>{content.commodityName}</View>
            <View className='qun-name'>
              <Text decode='true' className='qun-shop'>商场价：
                <Text decode='true' className='qun-price'>￥{content.price}</Text>
              </Text>
              <Text decode='true' className='qun-original' style="display:none;">原价：￥{specificationsList.originalprice}</Text>
            </View>
            <View className='qun-name qun-sname'>{zhuliList.ruleName}{zhuliList.pkTime}</View>
          </View>
          <View className='free-rule'>
            <RichText nodes={ruleList.content}></RichText>
          </View>
          <View className='now-pk'>
            {this.state.singlepersonLen}人正在PK
          </View>
          {singleperson.map((item, index) => (
          <View className='qun-pk'>
            <View className='pk-left'>
              <Image mode='scaleToFill' className='pk-pic' src={item.avatar != null ? item.avatar : 'https://minichat.g2ma.com/kedouimg/A6984900727459logo.png'}></Image>
              <Text className='pk-name'>{item.nickName ? item.nickName : '暂无'}</Text>
            </View>
            <View className='pk-left'>
              <View className='pk-remind'>
                <View className='remind-num'>
                  还差<Text className='pk-number'>{item.theNumberOfRemCoUsers ? item.theNumberOfRemCoUsers : 0}</Text>人
                </View>
                <View className='remind-time'>
                  {this.countDowns(this.state.nowDate, item.expiredCollageTime,this.state.content.id)}
                </View>
              </View>
              <View onClick={this.openjoin.bind(this,item.id,item.theNumberOfRemCoUsers,item.expiredCollageTime,item.shareUid)} className='pk-go'>
                去PK
              </View>
            </View>
          </View>
          ))}
          <View className='join-pk' style={this.state.joinnum ==1?'display:block':'display:none'} onTouchmove={this.preventTouchMove.bind(this)}>
            <View className='join-pks'>
              <View className='join-con'>
                <View className='join-close' onClick={this.closejoin.bind()}>X</View>
                <View className='join-title'>参与PK</View>
                <View className='join-time'>仅剩<Text className='pk-number'>{this.state.joinrenshu}</Text>个名额，<Text className='pk-number1'>{this.countDowns(this.state.nowDate,this.state.joinTime,this.state.content.id)}</Text>后结束</View>
                <View className='join-number'>
                  {joinlist.map((item, index) => (
                  <View className={item.type == 1 ? 'qun-pinzhu pinzhubor':'qun-pinzhu'}>
                    <View className='juin-pinzhu' style={item.type == 1 ? 'display:block':'display:none'}>拼主</View>
                    <Image mode='scaleToFill' className='join-pic' src={item.avatar ? item.avatar : 'https://minichat.g2ma.com/kedouimg/A6984900727459logo.png'}></Image>
                  </View>
                  ))}
                  {joinrenshulist.map((item, index) => (
                  <View className='qun-pinzhu'>
                    <Image mode='scaleToFill' className='join-pic' src='https://minichat.g2ma.com/kedouimg/wenhaox.png'></Image>
                  </View>
                  ))}
                </View>
                <View className='join-buts'>
                  <View className='join-but' onClick={this.canyupk.bind(this)}>参与PK</View>
                </View>
              </View>
            </View>
          </View>
          <View className='qun-details'>
            <View className='details-title'>商品详情</View>
            <View className='qun-photo'><RichText nodes={contents}></RichText></View>
          </View>
          <View className='qun-buy'>
            <View onClick={this.openalert.bind(this)} className='now-buy now-buycol2'>单独购</View>
            <View onClick={this.jump.bind(this,'/pages/grouplist/grouplists')} className='now-buy now-buycol1'>PK购</View>
          </View>
        </View>
        <View className='specifications' style={this.state.alertnum == 1?'display:block':'display:none'} onTouchmove={this.preventTouchMove.bind(this)}>
          <View className='specifications-con'>
            <View className='specifications-close' onClick={this.closealert.bind()}>X</View>
            <View className='specifications-title'>
              <View className='specifications-photo'>
                <Image className='specifications-pic' src={specificationsList.shopCommodity.logo}></Image>
              </View>
              <View className='specifications-name'>
                <View className='specifications-bname'>{specificationsList.shopCommodity.commodityName}</View>
                <View className='specifications-sname'>{specificationsList.shopCommodity.summary}</View>
                <View className='specifications-money'>{this.state.mallPrice}元</View>
              </View>
            </View>
            <View className='specifications-change'>
              {specificationsList.specInfor.map((item, index) => (
              <View>
                <View className='specifications-nav'>选择{item.availableSpecification == '统一规格' ? item.availableSpecification : '规格'}</View>
                <View className='specifications-changecon'>
                  {item.availableSpecification != '统一规格' ? 
                    item.availableSpecificationValue.map((item1, index1) => (
                      <Text className={this.state.indexs == index1?"specifications-active":"specifications-class"} onClick={this.openaddclass.bind(this,index1,item1)}>{item1}</Text>
                    )) 
                    : 
                    <Text className='specifications-active'>统一规格</Text>
                }
                </View>
              </View>
              ))}
              <View className='specifications-num'>
                <Text className='specifications-nums'>数量</Text>
                <View className='specifications-reduce' onClick={this.reducenum.bind()}>-</View>
                <View className='specifications-val'>{this.state.resultnum}</View>
                <View className='specifications-reduce' onClick={this.addnum.bind()}>+</View>
                <Text className='specifications-stock'>库存 <Text className='stock-num'>{this.state.amount}</Text></Text>
              </View>
              <View className='specifications-buy' onClick={this.opendetails.bind(this,'/pages/pkgo/confirmorder')}>立即购买</View>
            </View>
          </View>
        </View>
      </View>
    )
  }
}